/*
 * Copyright (c) 2016 Breezee.org. All Rights Reserved.
 */
/**
 * 将字符串格式为yyyy-MM-dd的字符串转换成日期
 * @param fDate
 * @returns {Date}
 */
function strToDate(fDate){
    var fullDate = fDate.split("-");
    return new Date(fullDate[0], fullDate[1]-1, fullDate[2], 0, 0, 0);
}

//检查时间是否符合粒度，比如粒度是小时的话，时间范围只能是一天之内
function checkDate(startDateStr,endDateStr,lidu){
    var resultObj = {'isSuccess' : true , 'msg' : '' };
    var startDate = strToDate(startDateStr);
    var endDate = strToDate(endDateStr);
    var intervalTime = endDate.getTime() - startDate.getTime();
    var days = Math.floor(intervalTime/(24*3600*1000));
    if(lidu == '3'){
        if(days > 31){
            resultObj.isSuccess = false;
            resultObj.msg = Dolphin.i18n.get("passenger.noWiderThanOneMonth");
        }
    }else if(lidu == '4'){
        if(days > 182){
            resultObj.isSuccess = false;
            resultObj.msg = Dolphin.i18n.get("passenger.noWiderThanMonths");
        }
    }else if(lidu == '5'){
        if(days > 365){
            resultObj.isSuccess = false;
            resultObj.msg = Dolphin.i18n.get("passenger.noWiderThanOneYear");
        }
    }else{
        if(days > 1){
            resultObj.isSuccess = false;
            resultObj.msg = Dolphin.i18n.get("passenger.noWiderThanOneDay");
        }
    }

    return resultObj;
}

$(function () {
    org.breezee.page = {
        const_vars : {
            bar_chartOption_legend_data : [] ,
            bar_chartOption_yAxis_data : [],
            bar_chartOption_series : [],
            line_chartOption_legend_data : [],
            line_chartOption_xAxis_data : [],
            line_chartOption_series : [],
            chartDiv : 'showDataDiv',
            shopCnt :  0,
            chartWidth : 0
        },

        init: function () {
            var loginCustomerId = $("#_loginCustomerId").val();
            var loginAccountId = $("#_loginAccountId").val();
            var loginVendorId = $("#_loginVendorId").val();
            if((loginCustomerId != null && loginCustomerId != "")
                || (loginVendorId != null && loginVendorId != "")){

                /*var optionUrl="/api/c666378c5d3b417d8e150c456a489d23@accountId="+loginAccountId;
              var ajaxType="get"
              var optionParam='{"properties":{}}'
              $("#customer_select").attr("optionUrl",optionUrl)
                  .attr("ajaxType",ajaxType)
                  .attr("optionParam", optionParam);*/

                let _this = $("#customer_select");
                Dolphin.ajax({
                    url: '/api/c666378c5d3b417d8e150c456a489d23@accountId='+loginAccountId,
                    type: Dolphin.requestMethod.GET,
                    async : false,
                    onSuccess: function (reData) {
                        _this.append(
                            '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                        $.each(reData.rows,function(index,obj){
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });
                $(".js-example-basic-single").select2();

            }else{
                /*var optionUrl="/api/742445c653654caaa4a1fa69eb651a9a"
                var ajaxType="post"
                var optionParam = '{"properties":{"category":"1"}}';
                $("#customer_select").attr("optionUrl",optionUrl)
                    .attr("ajaxType",ajaxType)
                    .attr("optionParam", optionParam);*/

                let _this = $("#customer_select");
                Dolphin.ajax({
                    url: '/api/742445c653654caaa4a1fa69eb651a9a',
                    type: Dolphin.requestMethod.POST,
                    async : false,
                    data: Dolphin.json2string({properties : {"category":"1"}}),
                    onSuccess: function (reData) {
                        _this.append(
                            '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                        $.each(reData.rows,function(index,obj){
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });
                $("#customer_select").select2();
            }

            Dolphin.form.parse();
            this._dataList = this.dataList('#dataList');
            this.initEvent();
            var shopCondition = {"selectCustomerId": loginCustomerId };
            if(loginCustomerId != null && loginCustomerId != ""){
                var _this = $("#shop_select");
                Dolphin.ajax({
                    url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                    type: Dolphin.requestMethod.POST,
                    async : false,
                    data: Dolphin.json2string({properties : shopCondition}),
                    onSuccess: function (reData) {
                        $.each(reData.rows,function(index,obj){
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });
            }
            $(".js-example-basic-multiple").select2();
        },
        /**
         * 初始化页面事件
         */
        initEvent: function () {
            let me = this;
            /**
             * 绑定回车事件，触发搜索
             */
            $(document).keypress(function(e) {
                var eCode = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
                if (eCode == 13){
                    $(".btn-query").click();
                }
            });

            $('.content-refresh').click(function () {
                me._userList.reload();
            });

            //以柱状图展现
            $('.showBar').click(function () {
                console.log('... enter showBar ...');
                console.log(me.const_vars);
                dolphinEcharts.bar_chart(me.const_vars.bar_chartOption_legend_data,
                    me.const_vars.bar_chartOption_yAxis_data,
                    me.const_vars.bar_chartOption_series,
                    me.const_vars.chartDiv,
                    me.const_vars.shopCnt,
                    me.const_vars.chartWidth);

            });
            //以折线图展现
            $('.showLine').click(function () {
                console.log('... enter showLine ...');
                console.log(me.const_vars);
                dolphinEcharts.line_chart(me.const_vars.line_chartOption_legend_data,
                    me.const_vars.line_chartOption_xAxis_data,
                    me.const_vars.line_chartOption_series,
                    me.const_vars.chartDiv);
            });

            //选择客户
            $("#customer_select").change(function(){
                $("#shop_select").empty();
                var queryConditionObj = {};
                queryConditionObj.selectCustomerId = $(this).val();
                if($("#followedFlag").is(':checked')){
                    queryConditionObj.followed = 'Y';
                }
                queryConditionObj.selectShopType = $("#shopType").val();
                var _this = $("#shop_select");

                Dolphin.ajax({
                    url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                    type: Dolphin.requestMethod.POST,
                    async : false,
                    data: Dolphin.json2string({properties : queryConditionObj}),
                    onSuccess: function (reData) {
                        $.each(reData.rows,function(index,obj){
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });
                    }
                });

                /*var condition = '{"properties":{"category":"3","parent_id_obj_ae": "'+$(this).val()+'"}}';
                 $("#shop_select").empty().attr("optionParam", condition);
                 Dolphin.form.parseSelect($(".query-form").find('#shop_select'));

                 if($("#shop_select_1").html() != undefined){
                 // $("#shop_select_1").empty().attr("optionParam", condition);
                 // Dolphin.form.parseSelect($(".query-form").find('#shop_select_1'));
                 $("#shop_select_1").html($("#shop_select").html());
                 }*/
            });

            //选择门店类型
            $("#shopType").change(function(){

                $("#shop_select").empty();

                var queryConditionObj = {};
                queryConditionObj.selectCustomerId = $("#customer_select").val()|| $("#_loginCustomerId").val();
                if($("#followedFlag").is(':checked')){
                    queryConditionObj.followed = 'Y';
                }
                queryConditionObj.selectShopType = $(this).val();

                var _this = $("#shop_select");

                Dolphin.ajax({
                    url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                    type: Dolphin.requestMethod.POST,
                    async : false,
                    data: Dolphin.json2string({properties : queryConditionObj}),
                    onSuccess: function (reData) {

                        $.each(reData.rows,function(index,obj){
                            _this.append(
                                '<option value="' + obj.id + '">'
                                + obj.name + '</option>');
                        });

                    }
                });

            });

            $(".btn_lidu").click(function () {
                $(".btn_select").removeClass('btn_select').addClass('btn_unselect');
                $(this).removeClass('btn_unselect').addClass('btn_select');
                var liduVal = $(this).data('type');
                $("#lidu_input").val(liduVal);
                if(liduVal == '3'){
                    $(".lidu_hour").hide();
                    // $(".lidu_day").show();
                    // $(".lidu_week").hide();
                    // $(".lidu_month").hide();
                    $("#btn_pressed_week").click();
                }else if(liduVal == '4'){
                    $(".lidu_hour").hide();
                    // $(".lidu_day").hide();
                    // $(".lidu_week").show();
                    // $(".lidu_month").hide();
                    $("#btn_pressed_month").click();
                }else if(liduVal == '5'){
                    $(".lidu_hour").hide();
                    // $(".lidu_day").hide();
                    // $(".lidu_week").hide();
                    // $(".lidu_month").show();
                    $("#btn_pressed_year").click();
                }else{
                    $(".lidu_hour").show();
                    // $(".lidu_day").hide();
                    // $(".lidu_week").hide();
                    // $(".lidu_month").hide();
                    $("#btn_pressed_day").click();
                }
            });

            $(".btn_daterange").click(function () {
                $(".btn_pressed").removeClass('btn_pressed').addClass('btn_unpressed');
                $(this).removeClass('btn_unpressed').addClass('btn_pressed');
                $("#startDate").val($(this).data('beg'));
                $("#endDate").val($(this).data('end'));
            });

            $(".btn_quota").click(function () {
                $(".btn_clicked").removeClass('btn_clicked').addClass('btn_unclicked');
                $(this).removeClass('btn_unclicked').addClass('btn_clicked');
            });

            $("#followedFlag").click(function () {
                var customerSelectVal = $("#customer_select").val();
                if(customerSelectVal != null
                    && customerSelectVal != ''){
                    var _this = $("#shop_select");
                    var queryConditionObj = {};
                    if($(this).is(':checked')){
                        queryConditionObj = {
                            "selectCustomerId" : customerSelectVal,
                            "followed" : "Y"};
                    }else{
                        queryConditionObj = {
                            "selectCustomerId" : customerSelectVal,
                        };
                    }
                    _this.empty();
                    Dolphin.ajax({
                        url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                        type: Dolphin.requestMethod.POST,
                        async : false,
                        data: Dolphin.json2string({properties : queryConditionObj}),
                        onSuccess: function (reData) {
                            _this.append(
                                '<option value="">--'+Dolphin.i18n.get("account.pleaseSelect")+'--</option>');
                            $.each(reData.rows,function(index,obj){
                                _this.append(
                                    '<option value="' + obj.id + '">'
                                    + obj.name + '</option>');
                            });
                        }
                    });
                }
            });

            //导出
            $(".btn-export").click(function () {

                var url = (org.breezee.context.contextPath=='/'?'':org.breezee.context.contextPath)
                    +'/api/fe1222f770a54abca1a4643345d5ed11';
                var form = $("<form />");
                form.attr({"style": "display: none", "target": '_blank', "method": "post", "action": url});
                $('body').append(form);
                var titleObj = {};
                $.each(me._dataList.__columns, function(index, obj){
                    titleObj[obj.code] = obj.title;
                });
                var value = Dolphin.json2string(titleObj);
                var input = $("<input>");
                input.attr({"name": "data[0]", "value": value, "type": "hidden"});
                form.append(input);

                $.each(me._dataList.data.rows, function(index, obj){
                    var value = Dolphin.json2string(obj);
                    var input = $("<input>");
                    input.attr({"name": "data["+(++index)+"]", "value": value, "type": "hidden"});
                    form.append(input);
                });

                var input = $("<input>");
                input.attr({"name": "excelName", "value": Dolphin.i18n.get("stores.comparison")+Dolphin.date2string(new Date(),'yyyyMMddhhmmss'), "type": "hidden"});
                form.append(input);
                form.submit();
                form.remove();
            });
            //分析
            $(".btn-query").click(function () {

                var shopArray = []

                var shopCondition = $(".shop_array").val();//查询条件 店铺
                var shopTypeCondition = $("#shopType").val();//查询条件 店铺类型
                var shopAreaCondition = $("#customer_select").val();//查询条件 区域

                if(shopCondition != null && shopCondition.length > 0){
                    shopArray = $.map(shopCondition,function(n,i){
                        return {id: n , name: $(".select2-selection__choice")[i].title};
                    });
                }
                else if( (shopTypeCondition != null && shopTypeCondition.length > 0)
                    || (shopAreaCondition != null && shopAreaCondition.length > 0) ){
                    Dolphin.ajax({
                        url: '/api/0ba568cd128743e4aa19c369c4b0ebd9',
                        type: Dolphin.requestMethod.POST,
                        data: Dolphin.json2string({properties : { "selectCustomerId" : (shopAreaCondition == null||shopAreaCondition=='' ? $("#_loginCustomerId").val() : shopAreaCondition) , "selectShopType" : shopTypeCondition}}),
                        async: false,
                        loading:true,
                        onSuccess: function (reData) {
                            if(reData.rows){
                                shopArray = $.map(reData.rows,function(n){
                                    return {id: n.id , name: n.name};
                                });
                            }
                        }
                    });
                }
                var queryConditionObj = Dolphin.form.getValue('.query-form');
                var lidu = queryConditionObj._lidu;
                var startDate = queryConditionObj._startDate;
                var endDate = queryConditionObj._endDate;
                if(queryConditionObj.shopType && !queryConditionObj._customerId){
                    queryConditionObj._customerId = $("#_loginCustomerId").val();
                }

                if(!(queryConditionObj._customerId
                    || queryConditionObj.shopType
                    || queryConditionObj.customer_id_obj_ae)){
                    Dolphin.alert(Dolphin.i18n.get("passenger.pleaseChooseOne"));
                    return;
                }


                // $('body > #loading').show(function(){

                    var shopIdArray = _.map(shopArray,function(obj,index){
                        return obj.id;
                    });
                    queryConditionObj._shopIds = shopIdArray;
                    Dolphin.ajax({
                        url: '/api/e6040baa72d740b6aac64dfef518860b',
                        type: Dolphin.requestMethod.POST,
                        loading: true,
                        data: Dolphin.json2string({properties: queryConditionObj}),
                        onSuccess: function (reData) {

                            var columns = [{
                                code: 'happenTime',
                                title: Dolphin.i18n.get("equipment.time"),
                                textAlign:'center',
                                formatter:function (val) {
                                    if(lidu == '3'){
                                        return val.substr(0, 10);
                                    }else if(lidu == '4'){
                                        var year = $("#startDate").val().substr(0,4);
                                        return getXDate(year,val) + ' 第'+val+'周';
                                    }else if(lidu == '5'){
                                        return val.substr(0,7);
                                    }else{
                                        var day = val.substr(0,10);
                                        var startHour = val.substr(11,2);
                                        var endHour = parseInt(startHour)+1
                                        return day + ' '+ startHour+':00-'+endHour+':00';
                                    }
                                }
                            }];
                            var compareDetailRows = [];

                            //以店铺或者设备来分组
                            var lineGroup = _.groupBy(reData.rows, function (obj) {
                                return obj.shopName;
                            });
                            var idx = 0;
                            _.each(lineGroup, function (shopArray, key) {
                                var legend = key;
                                var shopIdx = 'shop' + idx;
                                columns.push({
                                    code: shopIdx,
                                    title: legend
                                });

                                $.each(shopArray, function (index, obj) {
                                    if (compareDetailRows[index] == undefined) {
                                        compareDetailRows[index] = {happenTime: obj.happenTime};
                                    }
                                    compareDetailRows[index][shopIdx] = obj.dxin;
                                });
                                idx++;
                            });

                            //总共有多少个店铺或者设备
                            var shopCnt = shopIdArray.length;

                            me.barData(lineGroup,reData,lidu,shopCnt);
                            me.lineData(lineGroup,lidu);

                            //默认柱状图
                            $('.showBar').click();
                            /*if (shopCnt > 6) {

                            }else{
                                $('.showLine').click();
                            }*/

                            //对比数据明细
                            $("#dataList").empty();
                            me._dataList = new Dolphin.LIST({
                                panel: '#dataList',
                                idField: 'id',
                                columns: columns,
                                multiple: false,
                                rowIndex: true,
                                checkbox: false,
                                pagination:false,
                                data:{rows:compareDetailRows }

                            });
                        }
                    });

                    // $('body > #loading').hide();
                // });

            });

        },
        resetChartData : function(){
            let me = this;
            me.const_vars.bar_chartOption_legend_data = [] ;
            me.const_vars.bar_chartOption_yAxis_data = [];
            me.const_vars.bar_chartOption_series = [];
            me.const_vars.line_chartOption_legend_data = [];
            me.const_vars.line_chartOption_xAxis_data = [];
            me.const_vars.line_chartOption_series = [];
            me.const_vars.chartDiv = 'showDataDiv';
            me.const_vars.shopCnt =  0;
            me.const_vars.chartWidth = 0;
            me.const_vars.columns = [];
            me.const_vars.compareDetailRows = [];

        },

        barData : function(lineGroup,reData,lidu,shopCnt){
            let me = this;
            var tempSortMap = {}; //临时对象，用作存储店铺的客流总数，用于排序 格式：｛店铺名：客流总数｝
            var notEmptyArray = [];
            var idx = 0;
            _.each(lineGroup, function (shopArray, key) {
                var legend = key;
                var shopIdx = 'shop' + idx;

                var sum = _.reduce(shopArray, function (memo, obj) {
                    return memo + obj.dxin;
                }, 0);
                if (sum != 0 && sum != '0') {
                    notEmptyArray.push(sum);
                }
                tempSortMap[key] = sum;
                idx++;
            });
            //给原始数据增加total属性
            var newReData = _.map(reData.rows, function (obj, index) {
                obj.total = tempSortMap[obj.shopName];
                return obj;
            });

            var barGroup = _.groupBy(newReData, function (obj) {
                return obj.happenTime;
            });

            var chartOption_legend_data = [];
            var chartOption_yAxis_data = [];
            var chartOption_series = [];

            var idx = 0;
            var maxNum = 1000;
            var minNum = 0;
            _.each(barGroup, function (value, key) {
                if (lidu == '3') {//天
                    chartOption_legend_data[idx] = key.substr(5, 5);
                } else if (lidu == '4') {//周
                    var year = $("#startDate").val().substr(0, 4);
                    chartOption_legend_data[idx] = getXDate(year, key) + ' 第' + key + '周';
                } else if (lidu == '5') {//月
                    chartOption_legend_data[idx] = key.substr(5, 2);
                } else {//小时
                    chartOption_legend_data[idx] = key.substr(11, 2);
                }

                var yArray = [];
                var xArray = [];
                var newValue = _.sortBy(value, function (obj) {
                    return obj.total;
                });
                maxNum = Math.max.apply(null, notEmptyArray);
                minNum = Math.min.apply(null, notEmptyArray);
                $.each(newValue, function (index, obj) {
                    xArray.push(obj.dxin);
                    yArray.push(obj.shopName);
                });
                chartOption_yAxis_data = yArray;
                chartOption_series[idx] = {};
                chartOption_series[idx].name = chartOption_legend_data[idx];
                chartOption_series[idx].type = 'bar';
                chartOption_series[idx].stack = '总量';
                chartOption_series[idx].data = xArray;
                chartOption_series[idx].label = {normal: {show: true, position: 'insideRight'}};
                idx++;

            });

            me.const_vars.bar_chartOption_legend_data = chartOption_legend_data;
            me.const_vars.bar_chartOption_yAxis_data = chartOption_yAxis_data;
            me.const_vars.bar_chartOption_series = chartOption_series;
            me.const_vars.chartDiv = 'showDataDiv';
            me.const_vars.shopCnt = shopCnt;
            me.const_vars.chartWidth = parseInt(30/(minNum/maxNum));

        },
        lineData : function(lineGroup,lidu){
            let me = this;
            var chartOption_legend_data = [];
            var chartOption_xAxis_data = [];
            var chartOption_series = [];

            // var checkResult = checkDate(startDate,endDate,lidu);
            // if(!checkResult.isSuccess){
            //     Dolphin.alert(checkResult.msg);
            //     return;
            // }

            var idx = 0;
            _.each(lineGroup, function(value, key) {
                // shopArray.forEach(function(value,idx){
                var legend = key;
                var shopIdx = 'shop' + idx;

                chartOption_legend_data[idx] = legend;

                var xArray = [];
                var yArray = [];

                $.each(value ,function(index,obj){

                    if(lidu == '3'){//天
                        xArray.push(obj.happenTime.substr(5,5));
                    }else if(lidu == '4'){//周
                        var year = $("#startDate").val().substr(0,4);
                        xArray.push(getXDate(year,obj.happenTime) + ' 第'+obj.happenTime+'周');
                    }else if(lidu == '5'){//月
                        xArray.push(obj.happenTime.substr(5,2));
                    }else{//小时
                        xArray.push(obj.happenTime.substr(11,2));
                    }
                    yArray.push(obj.dxin);
                });
                chartOption_xAxis_data = xArray;
                chartOption_series[idx] = {};
                chartOption_series[idx].name = legend;
                chartOption_series[idx].type = 'line';
                // chartOption_series[idx].stack = '总量';
                chartOption_series[idx].data = yArray;

                idx++;
            });
            me.const_vars.line_chartOption_legend_data = chartOption_legend_data;
            me.const_vars.line_chartOption_xAxis_data = chartOption_xAxis_data;
            me.const_vars.line_chartOption_series = chartOption_series;
            me.const_vars.chartDiv = 'showDataDiv';

        },
        dataList: function (panelId) {}
    };
    org.breezee.page.init();



    /* 原来版本是通过多个下拉框模式实现多个店铺对比，现在改为一个下拉框多选来实现
    //添加店铺
    $(".btn_addShop").click(function(){

        var maxNum = 0;
        $(".shop_array").each(function(){
            var idVal = $(this).attr("id");
            var idValArray = idVal.split("_");
            if(idValArray.length > 2){
                maxNum = Math.max(maxNum, idValArray[2]);
            }
        });
        maxNum = maxNum + 1;
        $("#shop_select").clone(true).insertBefore("#addShop").attr("id","shop_select_"+maxNum)
            .attr("name","customer_id_obj_ae_"+maxNum);
    });
    //删除店铺
    $(".btn_delShop").click(function(){

        var maxNum = 0;
        $(".shop_array").each(function(){
            var idVal = $(this).attr("id");
            var idValArray = idVal.split("_");
            if(idValArray.length > 2){
                maxNum = Math.max(maxNum, idValArray[2]);
            }
        });
        $("#shop_select_"+maxNum).remove();
    });
    */


});